package com.triptogether.chat.adapters;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.triptogether.R;
import com.triptogether.utils.db.DBManager;
import com.triptogether.utils.db.models.Message;
import com.triptogether.utils.db.models.User;
import com.triptogether.utils.log.Logger;

public class MessagesListAdapter extends BaseAdapter {

	private final String TAG = Logger.makeLogTag(this.getClass());

	private List<Message> messagesList;
	private LayoutInflater mInflater;

	public MessagesListAdapter(Context context, List<Message> messages) {
		this.messagesList = (ArrayList<Message>) messages;
		this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public MessagesListAdapter(Context context, User fromUserId) {
		this(context, DBManager.getInstance(context).findMessagesFromUser(fromUserId));
	}

	/**
	 * Generate the view that represents the list. Choose the layout that should
	 * be displayed according to the {@link Message}
	 */
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// Check if the convert view is null, and inflate it when necessary
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.list_item_chat_message, null);
		}

		try {
			// get the message from the current position
			Message message = messagesList.get(position);

			// Initialize the view UI
			initItemViewUI(convertView, message);

		} catch (Exception e) {
			Logger.LOGE(TAG, e.getMessage());
		}

		return convertView;
	}

	/**
	 * Init the view of the item in the messages list.
	 * @param view The view to init.
	 * @param message The message to init the view with
	 */
	private void initItemViewUI(View view, Message message) {
		// initialize the views members
		TextView messageText = (TextView) view.findViewById(R.id.textview_message_text);
		TextView dateMessageReceived = (TextView) view.findViewById(R.id.textview_date_time_message_received);

		// set the values into the views
		messageText.setText(message.getMessageText());
		String formattedDateString = SimpleDateFormat.getInstance().format(message.getDateReceived());
		dateMessageReceived.setText(formattedDateString);
	}

	public void add(Message newMessage) {
		messagesList.add(newMessage);
		notifyDataSetChanged();
	}

	@Override
    public int getCount() {
		return messagesList.size();
    }

	@Override
    public Object getItem(int position) {
		return messagesList.get(position);
    }

	@Override
	public long getItemId(int position) {
		return messagesList.get(position).getId();
	}

}
